var activeSMResourceTab = 0;
var layout = null;
var emailaddress = "";

Ext.Ajax.request({
    url: "/addama-users/whoami",
    method: "GET",
    success: function(response) {
        var usersDecoded = Ext.util.JSON.decode(response.responseText);
        var userUri = usersDecoded.user;
        var splittedUser = userUri.split("/users/");
        emailaddress = splittedUser[1];
        if ((emailaddress == "jlin@systemsbiology.org" || emailaddress == "ascott@systemsbiology.org")) {
            mainPanel.add(groupsPanel, usersPanel, repoPanel);
        }
        initPref(emailaddress);
    },
    failure: function() {
        eventManager.fireStatusMessageEvent({ text: "You are not logged in", level: "error"});
    }
});

function initPref(userId) {
    Ext.Ajax.request({
        url: "/addama-rest/primary-repo/path/users/" + userId,
        method: "GET",
        success: function(response) {
            var userJson = Ext.util.JSON.decode(response.responseText);
            var limshome = userJson.limshome;
            if (limshome != null && limshome == "omics") {
                mainPanel.activate(sequencingPanel);
            } else if (limshome != null && limshome.indexOf("sample") != -1) {
                if (limshome.indexOf("yad") != -1) {
                    activeSMResourceTab = 1;
                }
                mainPanel.activate(samplesPanel);
            } else {
                mainPanel.activate(sequencingPanel);
                mainPanel.activate(samplesPanel);
                mainPanel.activate(contentPanel);                
            }
        },
        failure: function() {
            mainPanel.activate(contentPanel);
            mainPanel.activate(sequencingPanel);
            mainPanel.activate(samplesPanel);
            eventManager.fireStatusMessageEvent({ text: "Default to activating content panel", level: "error"});
        }
    });
}

/*
 function loadAnnouncements() {
 Ext.Ajax.request({
 url: "/addama-rest/dudley-sample/path/announcement/annotations",
 method: "GET",
 success: function(response) {
 var jsonObj = Ext.util.JSON.decode(response.responseText);
 var annCount = jsonObj.ann_entry;
 populateAnnouncementDiv(annCount);
 },
 failure: function (response) {
 Ext.getDom("announcements-div").innerHTML = "Failed getting LIMS Announcements -> " + new Date();
 }
 });
 };

 function seeAllAnnouncements() {
 alert("ToDo: Function has not been built");
 };


 function populateAnnouncementDiv(annCount) {
 //var annCount = announcementCount;
 //<A HREF="javascript:newwindow()" >Click Here!</A>
 if (annCount > 0 && announcementIter > 1) {
 //Ext.getDom("announcements-all-div").innerHTML = "<A HREF='javascript:seeAllAnnouncements()' >View All</A>";
 Ext.Ajax.request({
 url: "/addama-rest/dudley-sample/path/announcement/" + "ann" + annCount + "/annotations",
 method: "GET",
 success: function(response) {
 var jsonObj = Ext.util.JSON.decode(response.responseText);
 var annText = jsonObj.text;
 var annDate = jsonObj.annDate;
 latestAnnouncements = latestAnnouncements + annDate + " " + annText + "<br>";
 Ext.getDom("announcements-div").innerHTML = latestAnnouncements;
 announcementIter = announcementIter - 1;
 populateAnnouncementDiv(annCount - 1);
 },
 failure: function () {
 alert("failed getting text for annCount:" + annCount);
 Ext.getDom("announcements-div").innerHTML = "Failed getting LIMS Announcements -> " + new Date();
 }
 });
 }
 };
 */

var startPanel = {
    id: "main-content-start-panel",
    layout: "fit",
    bodyStyle: "padding:25px",
    contentEl: "main-content-start"
};

var repoViewPanel = {
    id: "main-content-repository-panel",
    layout: "fit",
    bodyStyle: "padding:25px",
    contentEl: "main-content-repository"
};

var folderViewPanel = {
    id: "main-content-folder-panel",
    layout: "fit",
    bodyStyle: "padding:25px",
    contentEl: "main-content-folder"
};

var fileViewPanel = {
    id: "main-content-file-panel",
    layout: "fit",
    bodyStyle: "padding:25px",
    contentEl: "main-content-file"
};

var contentPanel = new Ext.Panel({
    id: "panel-content-control",
    title: "Content Management",
    layout: "card",
    activeItem: 0,
    border: false,
    items: [ startPanel, repoViewPanel, folderViewPanel, fileViewPanel ]
});

contentPanel.on("activate", function () {
    loadAnnouncements(true);
});


var samplesPanel = new Ext.TabPanel({
    contentEl: "panel-samples",
    autoScroll: true,
    title: "Sample Management"
});

samplesPanel.on("activate", function () {
    if (!Dudley.lims.samplemgr.getSMLoaded()) {
        /*
        if (!Dudley.lims.sequencingmgr.getSeqLoaded()){
            Dudley.lims.sequencingmgr.loadSequencingManagement();
       }
       */
        Dudley.lims.samplemgr.loadSampleManagement(activeSMResourceTab);
    }
});

var galleryPanel = new Ext.TabPanel({
    contentEl: "panel-gallery",
    autoScroll: true,
    title: "Gallery"
});
galleryPanel.on("activate", function () {
    var loaded = Dudley.lims.gallerymgr.getGalleryLoaded();
    if (!loaded) {
        Dudley.lims.gallerymgr.loadGallery();
    }
});

/*
Place holder for Progeny Generation Web Workflow
 */
var progenyPanel = new Ext.TabPanel({
    contentEl: "panel-progeny",
    title: "Progeny Generation"
});
progenyPanel.on("activate", function () {
    alert("Progeny Generation Pages/Functions are TBD");
});

var sequencingPanel = new Ext.TabPanel({
    contentEl: "panel-sequencing",
    title: "Omics"
});
sequencingPanel.on("activate", function () {
    if (!Dudley.lims.sequencingmgr.getSeqLoaded()) {
            Dudley.lims.samplemgr.loadSampleManagement(activeSMResourceTab);
            Dudley.lims.sequencingmgr.loadSequencingManagement(function(){});        
    }
});

var usersPanel = new Ext.TabPanel({
    contentEl: "panel-users",
    title: "Users"
});
usersPanel.on("activate", function () {
    try {
        Ext.Ajax.request({
            url: "/addama-users/isAdmin",
            method: "GET",
            success: function(response) {
                var status = response.status;
                if (status == "200") {
                    Addama.users.UserAdmin.init();
                } else {
                    Ext.getDom("content-users").innerHTML = "You are not an administrator";
                }
            },
            failure: function () {
                repoPanel = {};
                Ext.getDom("content-users").innerHTML = "You are not an administrator";
            }
        });
    } catch (e) {
        Ext.getDom("content-users").innerHTML = "User Administration not Available: " + e;
    }

});
usersPanel.on("deactivate", function () {
    Ext.getDom("content-users").innerHTML = "";
});

var groupsPanel = new Ext.TabPanel({
    contentEl: "panel-groups",
    title: "Groups"
});

groupsPanel.on("activate", function () {
    try {
        Ext.Ajax.request({
            url: "/addama-users/isAdmin",
            method: "GET",
            success: function(response) {
                var status = response.status;
                if (status == "200") {
                    Addama.groups.GroupAdmin.init();
                } else {
                    Ext.getDom("content-groups").innerHTML = "You are not an administrator";
                }
            },
            failure: function () {
                repoPanel = {};
                Ext.getDom("content-groups").innerHTML = "You are not an administrator";
            }
        });
    } catch (e) {
        Ext.getDom("content-groups").innerHTML = "Group Administration not Available: " + e;
    }
});

groupsPanel.on("deactivate", function () {
    Ext.getDom("content-groups").innerHTML = "";
});

var repoPanel = new Ext.TabPanel({
    contentEl: "panel-repositories",
    title: "Repositories"
});

repoPanel.on("activate", function () {
    try {
        Ext.Ajax.request({
            url: "/addama-users/isAdmin",
            method: "GET",
            success: function(response) {
                var status = response.status;
                if (status == "200") {
                    Addama.jcr.RepoManager.init();
                } else {
                    Ext.getDom("content-repositories").innerHTML = "You are not an administrator";
                }
            },
            failure: function () {
                repoPanel = {};
                Ext.getDom("content-repositories").innerHTML = "You are not an administrator";
            }
        });

    } catch (e) {
        Ext.getDom("content-repositories").innerHTML = "Repository Administration not Available: " + e;
    }

});
repoPanel.on("deactivate", function () {
    Ext.getDom("content-repositories").innerHTML = "";
});

var mainPanel = new Ext.TabPanel({
    id: "panel-main-control",
    xtype: "tabpanel",
    region: "center",
    //activeTab: activeComponentTab,
    margins: "2 5 5 0",
    border: true,
    split: true,
    autoScroll: true,
    items:[ contentPanel, samplesPanel, sequencingPanel, galleryPanel],
    bbar:  new Ext.Toolbar({
        items : [
            [{
                        id:'signoutid',
                        text:'Sign out',
                        xtype: 'button',
                        cls: "x-btn-left",
                        icon: "images/logout.png",
                        handler:
                            function(){
                                LoggedInUser.signOut();
                            }
                        },
			/*{
                        id:'infoid',
                        text:'About',
                        xtype: 'button',
                        cls: "x-btn-right",
                        icon: "images/info.png",
                        handler:
                            function(){
                                 alert("info");
                                //LoggedInUser.signOut();
                            }
                        }*/
			statusBar]
        ]
    })
});

// event handlers
eventManager.registerNodeSelectListener(function(node) {
    mainPanel.setActiveTab(0);
    var nodeCls = node.attributes.cls;
    layout = contentPanel.layout;
    if (layout) {
        if (nodeCls == "repository") {
            layoutRepositoryViewPort(layout, node);
        } else if (nodeCls == "file") {
            layoutFileViewPort(layout, node);
        } else if (nodeCls == "folder") {
            layoutFolderViewPort(layout, node);
        } else {
            layout.setActiveItem("main-content-start-panel");
        }
    }
});



